// pages/user-active-report/user-active-report.js
const app = getApp()

Page({
  data: {
    orders: [],
    orderModels: [],
    selectedOrder: null,
    selectedModel: null,
    quantity: '',
    workHours: '',
    startTime: '',
    endTime: '',
    workDate: '',
    remark: '',
    loading: true,
    submitting: false,
    productItems: [], // 产品编号列表
    images: [] // 通用图片列表
  },

  onLoad() {
    this.loadOrders()
    this.setWorkDate()
  },

  onShow() {
    // 如果已有订单数据，重新加载
    if (this.data.orders.length === 0) {
      this.loadOrders()
    }
  },

  onPullDownRefresh() {
    this.setData({
      refreshing: true
    })
    this.loadOrders().then(() => {
      wx.stopPullDownRefresh()
      this.setData({
        refreshing: false
      })
    })
  },

  // 设置工作日期为今天
  setWorkDate() {
    const today = new Date()
    const year = today.getFullYear()
    const month = String(today.getMonth() + 1).padStart(2, '0')
    const day = String(today.getDate()).padStart(2, '0')
    this.setData({
      workDate: `${year}-${month}-${day}`
    })
  },

  // 加载订单列表
  loadOrders() {
    console.log('开始加载订单列表')
    this.setData({ loading: true })
    
    return app.userRequest({
      url: '/getOrders'
    }).then((res) => {
      console.log('获取订单列表成功:', res)
      this.setData({
        orders: res.data || [],
        loading: false
      })
    }).catch((err) => {
      console.error('获取订单列表失败:', err)
      this.setData({
        loading: false
      })
      wx.showToast({
        title: '获取订单失败',
        icon: 'none'
      })
    })
  },

  // 订单选择
  onOrderChange(e) {
    console.log('=== 订单选择变化 ===')
    console.log('选择索引:', e.detail.value)
    console.log('所有订单:', this.data.orders)
    
    const orderIndex = e.detail.value
    const order = this.data.orders[orderIndex]
    
    console.log('选中的订单:', order)
    console.log('订单ID:', order ? order.id : '无')
    
    this.setData({
      selectedOrder: order,
      selectedModel: null,
      orderModels: [],
      quantity: '',
      productItems: []
    })
    
    if (order && order.id) {
      console.log('开始加载订单型号，订单ID:', order.id)
      this.loadOrderModels(order.id)
    } else {
      console.log('订单无效或没有ID，不加载型号')
    }
  },

  // 加载订单型号
  loadOrderModels(orderId) {
    console.log('=== 开始加载订单型号 ===')
    console.log('orderId:', orderId)
    
    const requestUrl = '/getOrderModels?order_id=' + orderId
    console.log('请求URL:', requestUrl)
    
    app.userRequest({
      url: requestUrl,
      method: 'GET'
    }).then((res) => {
      console.log('=== 获取订单型号成功 ===')
      console.log('响应数据:', res)
      
      if (Array.isArray(res.data)) {
        // 计算每个型号的可报工数量（总数量 - 已分工数量 - 主动报工数量）
        const orderModelsWithAvailableQuantity = res.data.map(model => {
          const totalQuantity = model.order_quantity || 0
          const allocatedQuantity = model.allocated_quantity || 0
          const activeReportQuantity = model.active_report_quantity || 0
          const availableQuantity = Math.max(0, totalQuantity - allocatedQuantity - activeReportQuantity)
          
          return {
            ...model,
            available_quantity: availableQuantity, // 可报工数量
            allocated_quantity: allocatedQuantity, // 已分工数量
            active_report_quantity: activeReportQuantity, // 主动报工数量
            order_quantity: totalQuantity // 总数量
          }
        })
        
        console.log('计算后的型号数据:', orderModelsWithAvailableQuantity)
        
        this.setData({
          orderModels: orderModelsWithAvailableQuantity
        })
        console.log('页面数据已更新，orderModels长度:', this.data.orderModels.length)
      } else {
        console.log('数据不是数组，可能是:', res.data)
        wx.showToast({
          title: '数据格式错误',
          icon: 'none'
        })
      }
    }).catch((err) => {
      console.error('=== 获取订单型号失败 ===')
      console.error('错误对象:', err)
      
      wx.showToast({
        title: err.msg || '获取型号失败',
        icon: 'none'
      })
    })
  },

  // 型号选择
  onModelChange(e) {
    const modelIndex = e.detail.value
    const model = this.data.orderModels[modelIndex]
    
    this.setData({
      selectedModel: model,
      quantity: '',
      productItems: []
    })
  },

  // 数量输入
  onQuantityInput(e) {
    const quantity = parseInt(e.detail.value) || 0
    const maxQuantity = this.data.selectedModel ? this.data.selectedModel.available_quantity : 0
    
    // 限制数量不能超过可报工数量
    if (quantity > maxQuantity) {
      wx.showToast({
        title: `数量不能超过可报工数量${maxQuantity}`,
        icon: 'none'
      })
      this.setData({
        quantity: maxQuantity.toString()
      })
      return
    }
    
    this.setData({
      quantity: quantity.toString()
    })
    
    // 生成产品编号列表
    this.generateProductItems(quantity)
  },

  // 工时输入
  onWorkHoursInput(e) {
    this.setData({
      workHours: e.detail.value
    })
  },

  // 开始时间变化
  onStartTimeChange(e) {
    const startTime = e.detail.value
    this.setData({
      startTime: startTime
    })
    
    // 自动计算工时
    this.calculateWorkHours()
  },

  // 结束时间变化
  onEndTimeChange(e) {
    const endTime = e.detail.value
    this.setData({
      endTime: endTime
    })
    
    // 自动计算工时
    this.calculateWorkHours()
  },

  // 自动计算工时
  calculateWorkHours() {
    const { startTime, endTime, workDate } = this.data
    
    if (startTime && endTime && workDate) {
      const start = new Date(`${workDate} ${startTime}`)
      const end = new Date(`${workDate} ${endTime}`)
      
      if (end > start) {
        const hours = (end - start) / (1000 * 60 * 60)
        this.setData({
          workHours: hours.toFixed(2)
        })
      }
    }
  },

  // 工作日期变化
  onWorkDateChange(e) {
    this.setData({
      workDate: e.detail.value
    })
  },

  // 备注输入
  onRemarkInput(e) {
    this.setData({
      remark: e.detail.value
    })
  },

  // 生成产品编号列表
  generateProductItems(quantity) {
    if (!quantity || quantity <= 0) {
      this.setData({
        productItems: []
      })
      return
    }

    // 调用后端API生成唯一的产品编号
    this.generateUniqueItemNos(quantity)
  },

  // 调用后端API生成唯一的产品编号
  generateUniqueItemNos(quantity) {
    if (!this.data.selectedOrder || !this.data.selectedModel) {
      wx.showToast({
        title: '请先选择订单和产品型号',
        icon: 'none'
      })
      return
    }

    wx.showLoading({
      title: '生成编号中...'
    })

    app.userRequest({
      url: '/generateItemNos',
      method: 'POST',
      data: {
        order_id: this.data.selectedOrder.id,
        model_id: this.data.selectedModel.model_id,
        process_id: this.data.selectedModel.process_id,
        quantity: quantity
      }
    }).then((res) => {
      wx.hideLoading()
      console.log('生成产品编号成功:', res)
      
      const productItems = res.data.map(itemNo => ({
        item_no: itemNo,
        images: [],
        hasImages: false
      }))

      this.setData({
        productItems: productItems
      })
    }).catch((err) => {
      wx.hideLoading()
      console.error('生成产品编号失败:', err)
      
      // 如果API调用失败，使用简单的编号生成作为备选
      const productItems = []
      for (let i = 1; i <= quantity; i++) {
        const itemNo = String(i).padStart(3, '0') // 001, 002, 003...
        productItems.push({
          item_no: itemNo,
          images: [],
          hasImages: false
        })
      }

      this.setData({
        productItems: productItems
      })

      wx.showToast({
        title: '编号生成失败，使用默认编号',
        icon: 'none'
      })
    })
  },

  // 选择图片
  chooseImage(e) {
    const itemNo = e.currentTarget.dataset.itemNo
    console.log('选择图片，产品编号:', itemNo)
    
    const productItems = this.data.productItems
    const itemIndex = productItems.findIndex(item => item.item_no === itemNo)
    
    if (itemIndex === -1) {
      console.error('未找到产品编号:', itemNo)
      return
    }
    
    const currentImages = productItems[itemIndex].images
    const remainingCount = 9 - currentImages.length
    
    if (remainingCount <= 0) {
      wx.showToast({
        title: '已达到最大图片数量',
        icon: 'none'
      })
      return
    }
    
    wx.chooseImage({
      count: remainingCount,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        if (res.tempFilePaths && res.tempFilePaths.length > 0) {
          // 上传图片
          this.uploadImages(res.tempFilePaths, itemNo)
        }
      },
      fail: (err) => {
        console.error('选择图片失败:', err)
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        })
      }
    })
  },

  // 上传图片
  uploadImages(tempFilePaths, itemNo) {
    console.log('开始上传图片，文件路径:', tempFilePaths, '产品编号:', itemNo)
    
    if (!tempFilePaths || tempFilePaths.length === 0) {
      wx.showToast({
        title: '没有选择文件',
        icon: 'none'
      })
      return
    }
    
    wx.showLoading({
      title: '上传中...'
    })

    const uploadPromises = tempFilePaths.map((filePath, index) => {
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: app.globalData.userApiUrl + '/uploadImage',
          filePath: filePath,
          name: 'file',
          header: {
            'Authorization': 'Bearer ' + wx.getStorageSync('token')
          },
          success: (res) => {
            try {
              const data = JSON.parse(res.data)
              if (data.code === 1) {
                resolve(data.data.url)
              } else {
                reject(new Error(data.msg))
              }
            } catch (e) {
              reject(new Error('响应解析失败'))
            }
          },
          fail: (err) => {
            reject(err)
          }
        })
      })
    })

    Promise.all(uploadPromises).then(imageUrls => {
      console.log('所有图片上传成功:', imageUrls)
      
      // 更新产品编号的图片列表
      const productItems = this.data.productItems
      const itemIndex = productItems.findIndex(item => item.item_no === itemNo)
      
      if (itemIndex !== -1) {
        productItems[itemIndex].images = [...productItems[itemIndex].images, ...imageUrls]
        productItems[itemIndex].hasImages = productItems[itemIndex].images.length > 0
        
        this.setData({
          productItems: productItems
        })
      }
      
      wx.hideLoading()
      wx.showToast({
        title: '上传成功',
        icon: 'success'
      })
    }).catch(err => {
      console.error('图片上传失败:', err)
      wx.hideLoading()
      wx.showToast({
        title: '上传失败: ' + (err.message || err.errMsg || '未知错误'),
        icon: 'none',
        duration: 3000
      })
    })
  },

  // 选择通用图片（用于计时报工）
  chooseGeneralImage() {
    const currentImages = this.data.images || []
    const remainingCount = 9 - currentImages.length
    
    if (remainingCount <= 0) {
      wx.showToast({
        title: '已达到最大图片数量',
        icon: 'none'
      })
      return
    }
    
    wx.chooseImage({
      count: remainingCount,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        if (res.tempFilePaths && res.tempFilePaths.length > 0) {
          this.uploadGeneralImages(res.tempFilePaths)
        }
      },
      fail: (err) => {
        console.error('选择通用图片失败:', err)
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        })
      }
    })
  },

  // 上传通用图片（用于计时报工）
  uploadGeneralImages(tempFilePaths) {
    console.log('开始上传通用图片，文件路径:', tempFilePaths)
    
    if (!tempFilePaths || tempFilePaths.length === 0) {
      wx.showToast({
        title: '没有选择文件',
        icon: 'none'
      })
      return
    }
    
    wx.showLoading({
      title: '上传中...'
    })

    const uploadPromises = tempFilePaths.map((filePath, index) => {
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: app.globalData.userApiUrl + '/uploadImage',
          filePath: filePath,
          name: 'file',
          header: {
            'Authorization': 'Bearer ' + wx.getStorageSync('token')
          },
          success: (res) => {
            try {
              const data = JSON.parse(res.data)
              if (data.code === 1) {
                resolve(data.data.url)
              } else {
                reject(new Error(data.msg))
              }
            } catch (e) {
              reject(new Error('响应解析失败'))
            }
          },
          fail: (err) => {
            reject(err)
          }
        })
      })
    })

    Promise.all(uploadPromises).then(imageUrls => {
      console.log('所有通用图片上传成功:', imageUrls)
      
      // 更新通用图片列表
      const images = this.data.images || []
      const newImages = [...images, ...imageUrls]
      
      this.setData({
        images: newImages
      })
      
      wx.hideLoading()
      wx.showToast({
        title: '上传成功',
        icon: 'success'
      })
    }).catch(err => {
      console.error('通用图片上传失败:', err)
      wx.hideLoading()
      wx.showToast({
        title: '上传失败: ' + (err.message || err.errMsg || '未知错误'),
        icon: 'none',
        duration: 3000
      })
    })
  },

  // 删除图片
  deleteImage(e) {
    const itemNo = e.currentTarget.dataset.itemNo
    const index = e.currentTarget.dataset.index
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这张图片吗？',
      success: (res) => {
        if (res.confirm) {
          if (itemNo) {
            // 删除产品编号的图片
            const productItems = this.data.productItems
            const itemIndex = productItems.findIndex(item => item.item_no === itemNo)
            
            if (itemIndex !== -1) {
              productItems[itemIndex].images.splice(index, 1)
              productItems[itemIndex].hasImages = productItems[itemIndex].images.length > 0
              
              this.setData({
                productItems: productItems
              })
            }
          } else {
            // 删除通用图片
            const images = this.data.images || []
            images.splice(index, 1)
            this.setData({
              images: images
            })
          }
        }
      }
    })
  },

  // 预览图片
  previewImage(e) {
    const url = e.currentTarget.dataset.url
    wx.previewImage({
      urls: [url],
      current: url
    })
  },

  // 提交主动报工
  submitActiveReport() {
    const { selectedOrder, selectedModel, quantity, workHours, startTime, endTime, workDate, remark, productItems, images } = this.data
    
    if (!selectedOrder) {
      wx.showToast({
        title: '请选择订单',
        icon: 'none'
      })
      return
    }
    
    if (!selectedModel) {
      wx.showToast({
        title: '请选择产品型号和工序',
        icon: 'none'
      })
      return
    }
    
    if (!workDate) {
      wx.showToast({
        title: '请选择工作日期',
        icon: 'none'
      })
      return
    }
    
    if (!quantity || quantity <= 0) {
      wx.showToast({
        title: '请输入数量',
        icon: 'none'
      })
      return
    }
    
    if (!workHours || workHours <= 0) {
      wx.showToast({
        title: '请输入工作时长',
        icon: 'none'
      })
      return
    }

    // 检查计件报工是否所有产品都上传了图片
    if (quantity > 0) {
      const itemsWithoutImages = productItems.filter(item => !item.hasImages)
      if (itemsWithoutImages.length > 0) {
        wx.showToast({
          title: `产品${itemsWithoutImages.map(item => item.item_no).join(',')}还未上传图片`,
          icon: 'none'
        })
        return
      }
    }

    const orderModel = `${selectedModel.model_id}:${selectedModel.process_id}`
    
    const data = {
      order_id: selectedOrder.id,
      order_model: orderModel,
      work_date: workDate,
      remark: remark,
      quantity: quantity,
      work_hours: workHours,
      start_time: startTime,
      end_time: endTime
    }

    // 添加产品编号和图片数据
    if (productItems && productItems.length > 0) {
      data.product_items = productItems.map(item => ({
        item_no: item.item_no,
        images: item.images
      }))
    }

    // 如果有通用图片，也包含进去
    if (images && images.length > 0) {
      data.images = images
    }

    this.setData({
      submitting: true
    })

    app.userRequest({
      url: '/activeReport',
      method: 'POST',
      data: data
    }).then((res) => {
      wx.showToast({
        title: '提交成功',
        icon: 'success'
      })
      
      // 重置表单
      this.setData({
        selectedOrder: null,
        selectedModel: null,
        orderModels: [],
        quantity: '',
        workHours: '',
        startTime: '',
        endTime: '',
        remark: '',
        productItems: [],
        images: [],
        submitting: false
      })
    }).catch((err) => {
      this.setData({
        submitting: false
      })
      wx.showToast({
        title: err.msg || '提交失败',
        icon: 'none'
      })
    })
  },

  // 刷新数据
  refreshData() {
    this.loadOrders()
  }
}) 